import requests
import re
import os
from concurrent.futures import ThreadPoolExecutor

# 请求的URL和headers
url = "https://www.freepik.com/free-photos-vectors/blue-background"
headers = {
    "user-agent":
               "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0"
}

# 下载图片的函数
def download_image(image_link, image_name, folder_path):
    try:
        response = requests.get(image_link, headers=headers)
        if response.status_code == 200:
            with open(os.path.join(folder_path, "{}.jpg".format(image_name)), "wb") as img:
                img.write(response.content)
            print(f"{image_name}.jpg 下载成功")
        else:
            print(f"{image_name}.jpg 下载失败, 状态码: {response.status_code}")
    except Exception as e:
        print(f"{image_name}.jpg 下载失败, 错误: {e}")

# 主函数，执行多线程下载
def main():
    # 发送请求，获取页面响应
    response = requests.get(url=url, headers=headers)

    # 使用正则表达式获取页面中所有的src内容
    parr = re.compile('alt="(.*?)".data-src="(.*?)"')
    image_list = re.findall(parr, response.text)

    # 创建存放图片的文件夹
    folder_path = "freepik"
    if not os.path.exists(folder_path):
        os.mkdir(folder_path)

    # 使用 ThreadPoolExecutor 实现多线程下载
    with ThreadPoolExecutor(max_workers=5) as executor:
        for i in image_list:
            name, src = i[0], i[1]
            executor.submit(download_image, src, name, folder_path)

if __name__ == "__main__":
    main()

